#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import asyncio
import logging
from datetime import datetime
from sqlalchemy import select

# 添加项目根目录到sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from models import Contract, Base, engine
from models.base import SessionLocal
from services.exchange.adapters.gate_adapter import GateAdapter
from services.exchange.interface import ExchangeType

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

async def fetch_gate_contracts():
    """获取Gate.io交易所合约信息 - 精简版"""
    logger.info("开始获取Gate.io合约信息...")
    
    # 初始化Gate.io适配器
    gate = GateAdapter()
    
    try:
        # 默认使用usdt结算
        settle = 'usdt'
        
        # 调用API获取合约列表
        endpoint = f"/futures/{settle}/contracts"
        response = await gate.http_client.request(
            method="GET",
            url=endpoint
        )
        
        contracts = []
        for item in response:
            contract = Contract(
                exchange="GATE",  # 使用字符串代替枚举
                symbol=item['name'],
                mark_price_round=str(item.get('mark_price_round', '')),
                quanto_multiplier=str(item.get('quanto_multiplier', '')),
                is_active=True  # 默认活跃状态
            )
            contracts.append(contract)
        
        logger.info(f"获取到{len(contracts)}个Gate.io合约")
        return contracts
    
    except Exception as e:
        logger.error(f"获取Gate.io合约信息失败: {e}")
        return []
    finally:
        # 关闭HTTP客户端
        await gate.close()

async def save_contracts(contracts):
    """保存合约信息到数据库 - 精简版"""
    logger.info(f"开始保存{len(contracts)}个合约到数据库...")
    
    # 获取数据库会话
    session = SessionLocal()
    
    try:
        # 处理每个合约
        for contract in contracts:
            # 检查合约是否已存在
            existing = session.execute(
                select(Contract).where(
                    Contract.exchange == contract.exchange,
                    Contract.symbol == contract.symbol
                )
            ).scalar_one_or_none()
            
            if existing:
                # 更新现有合约
                logger.debug(f"更新合约: {contract.symbol}")
                existing.mark_price_round = contract.mark_price_round
                existing.quanto_multiplier = contract.quanto_multiplier
                existing.updated_at = datetime.now()
            else:
                # 添加新合约
                logger.debug(f"添加合约: {contract.symbol}")
                session.add(contract)
        
        # 提交事务
        session.commit()
        logger.info("合约信息保存成功")
    
    except Exception as e:
        # 回滚事务
        session.rollback()
        logger.error(f"保存合约信息失败: {e}")
    
    finally:
        # 关闭会话
        session.close()

async def main():
    """主函数"""
    logger.info("开始获取交易所合约信息...")
    
    # 获取Gate.io合约信息
    gate_contracts = await fetch_gate_contracts()
    
    # 保存合约信息到数据库
    await save_contracts(gate_contracts)
    
    logger.info("合约信息获取和保存完成")

if __name__ == "__main__":
    # 创建表（如果不存在）
    Base.metadata.create_all(engine)
    
    # 运行主函数
    asyncio.run(main()) 